#!/usr/bin/env bash

#####################################################################
#
# This script manages app build numbers.
# It returns the next build number to be used.
# The limit of size of the number is signed int, which is 2147483647.
#
# These numbers are used to mark app artifacts for:
# * Play Store - versionCode attribute (gradle)
# * Apple Store - CFBundleVersion attribute (plutil)
#
# For more details see:
# * https://developer.android.com/studio/publish/versioning
# * https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
#
# History:
#
# This script used to tag builds with `build-[0-9]+` tags.
# Since only release builds actually get uploaded to Play or Apple
# stores only then is the uniqueness of numbers checked.
# Because of that we are fine using just hour granurality.
#
#####################################################################

# Fail on first error
set -e

DEV_BUILD_NUMBER=9999

SCRIPTPATH="$(cd "$(dirname "$0")" ; pwd -P)"
ROOT_PATH="${SCRIPTPATH}/../../"
BUILD_NUMBER_FILE="${ROOT_PATH}/BUILD_NUMBER"

# If running under Jenkins use a timestamp-based build number.
# That build number is generated by the scripts/version/gen_build_no.sh script.
if [[ -f "${BUILD_NUMBER_FILE}" ]]; then
    echo "Build number file found, using: $(cat ${BUILD_NUMBER_FILE})" 1>&2
    cat "${BUILD_NUMBER_FILE}"
else
    echo "Build number file missing, using: ${DEV_BUILD_NUMBER}" 1>&2
    echo "${DEV_BUILD_NUMBER}"
fi
